/* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>  
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define MAXLINE 80
#define SERV_PORT 9000

void
sig_handle (int signo) {
    pid_t   pid;
    int     stat;

    pid = wait(&stat);

    printf("Worker Process %d Terminated\n", pid);

    return;
}

int
main (void) {
    struct sockaddr_in servaddr, cliaddr;

    socklen_t cliaddr_len;

    int listenfd, clientfd;

    char buffer[MAXLINE];

    int i, n;

    // socket()打开一个网络通讯端口, 并返回一个文件描述符listenfd; SOCK_STREAM表示面向流的传输协议
    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    // bzero()会将内存块(字符串)的前n个字节清零
    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    // bind()的作用是将参数listenfd和servaddr绑定在一起
    bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    // 开始监听listenfd所描述的地址和端口号(支持最多20个客户端)
    listen(listenfd, 20);

    printf("Listen on %s:%d\n", "0.0.0.0", SERV_PORT);

    while (1) {
        cliaddr_len = sizeof(cliaddr);

        // accept将阻塞进程直到有客户端链接
        clientfd = accept(listenfd, (struct sockaddr *) &cliaddr, &cliaddr_len);

        printf("Client connected: \n");

        // 处理子进程结束信号
        signal(SIGCHLD, sig_handle);

        if (clientfd) {
            // 每个客户端链接clientfd由子进程worker处理
            pid_t worker = fork();

            if (worker == 0) { //worker进程
                while (1) {
                    // 从clienfd读取信息
                    n = read(clientfd, buffer, MAXLINE);

                    // ntohs()将一个16位数由网络字节顺序转换为主机字节顺序
                    printf("Received %s from %d \n", buffer, ntohs(cliaddr.sin_port));

                    for (i = 0; i < n; i++) {
                        buffer[i] = toupper(buffer[i]);
                    }

                    write(clientfd, buffer, n);
                }
            }
        }
    }
}
